﻿using System.Security.Cryptography;
using System.Text;

namespace Aurora.Security.AES
{
    public static class SecurityAESCore
    {
        #region 对称加密

        /// <summary>
        /// 默认加密密钥
        /// </summary>
        private const string defaultKey = SecurityAESContext.DefaultKey ;

        private const string defaultIv = SecurityAESContext.DefaultIv ;

        /// <summary>
        /// AES-128-CBC 加密 与 finance_micro_services_v1项目加密方法一致
        /// </summary>
        /// <param name="value">需要加密的内容</param>
        /// <param name="key">密钥,必须是32位字符串的Base64编码</param>
        /// <param name="iv">必须是16位字符串的Base64编码</param>
        /// <returns></returns>
        public static string ToAes128EncryptString(this string value, string key = defaultKey, string iv = defaultIv)
        {
            var aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.BlockSize = 128;
            aes.Padding = PaddingMode.PKCS7;

            var keyBytes =  Encoding.UTF8.GetBytes(key);
            var ivBytes =  Encoding.UTF8.GetBytes(iv);
            var toEncryptArray = Encoding.UTF8.GetBytes(value);

            aes.Key = keyBytes;
            aes.IV = ivBytes;

            var cTransform = aes.CreateEncryptor();
            var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray);
        }

        /// <summary>
        /// AES-128-CBC 解密
        /// </summary>
        /// <param name="value">Base64编码的加密内容</param>
        /// <param name="key">密钥,必须是32位字符串的Base64编码</param>
        /// <param name="iv">必须是16位字符串的Base64编码</param>
        /// <returns></returns>
        public static string ToAes128DecryptString(this string value, string key = defaultKey, string iv = defaultIv)
        {
            var aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.BlockSize = 128;
            aes.Padding = PaddingMode.PKCS7;

            var keyBytes = Encoding.UTF8.GetBytes(key);
            var ivBytes = Encoding.UTF8.GetBytes(iv);
            var encryptDataBytes = Convert.FromBase64String(value);

            aes.Key = keyBytes;
            aes.IV = ivBytes;

            var transform = aes.CreateDecryptor();
            var decryptDataBytes = transform.TransformFinalBlock(encryptDataBytes, 0, encryptDataBytes.Length);
            return Encoding.UTF8.GetString(decryptDataBytes);
        }

        #endregion
    }
}